package com.zjitc.backend_shop.security;

import com.alibaba.fastjson2.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zjitc.backend_shop.pojo.po.LoginUser;
import com.zjitc.backend_shop.utils.CheckResult;
import com.zjitc.backend_shop.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import io.swagger.v3.core.util.Json;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import tk.mybatis.mapper.util.StringUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;

/*
    @author： 尤安托
    @date： 2025/4/14 14:56
*/
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    private final ObjectMapper objectMapper = new ObjectMapper();
    private static final String URL_WHITELIST[] ={"/login","/logout","/home/**","/list","/admin/login"} ;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String token = request.getHeader("jwt");
        System.out.println("请求url:"+request.getRequestURI());
        if(StringUtil.isEmpty(token) || new ArrayList<String>(Arrays.asList(URL_WHITELIST)).contains(request.getRequestURI())){
            chain.doFilter(request,response);
            return;
        }
        if(!StringUtils.hasLength(token)){
            throw new RuntimeException("token为空");
        }
        LoginUser loginUser=null;
        try{
            Claims claims=JwtUtils.validateToken(token);
            String loginUserString = claims.getSubject();
            loginUser = JSON.parseObject(loginUserString, LoginUser.class);
        }catch(Exception e){
            throw new RuntimeException("token校验失败");
        }
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser,null,loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        chain.doFilter(request,response);
    }
}
